package gateway

import (
	"github.com/gin-gonic/gin"
	"gogame/gameservice"
	"gogame/gameservice/service"
	"gogame/logger"
	"gogame/server/network/ws"
	"gogame/server/rpcx"
	"net/http"
)

type Service struct {
	service.Service
	webSocketListener *ws.WebsocketServer // websocket server
	RpcManage         *RpcManage          // rpc管理
	LoginQueue        *loginQueue         // 登陆队列
}

// NewService 创建gateway service
func NewService() service.IService {
	_service := &Service{
		LoginQueue: NewLoginQueue(),
	}
	_service.RpcManage = NewRpcManage(_service)
	return _service
}

func init() {
	gameservice.Service2NewFunc["gateway"] = NewService
}

// InitRoute 路由
func (s *Service) InitRoute(listen string) {
	// ws
	path2WsHandle := map[string]ws.WebSocketHandle{
		// 游戏逻辑处理
		"/gateway": func(request *http.Request) ws.WebsocketInterFace {
			return NewGatewayApp(s, "gateway")
		},
	}

	// http
	path2HttpHandle := map[string]gin.HandlerFunc{
		// gateway服务停止
		"/stop_gateway": func(ctx *gin.Context) {
			gameservice.StopService("gateway", s.GetListen())
			ctx.JSON(200, gin.H{
				"message": "ok",
			})
		},
	}

	s.webSocketListener = &ws.WebsocketServer{
		Path2WsHandle:   path2WsHandle,
		Path2HttpHandle: path2HttpHandle,
	}
}

// StartServer 开始服务
func (s *Service) StartServer(serviceName, listen string) {
	// 初始化日志
	logger.InitLog("gateway", serviceName)
	// rpcManage开启
	s.RpcManage.Run(serviceName, listen, rpcx.Api, rpcx.CrossApi)
	// 路由
	s.InitRoute(listen)
	// start websocket listen...
	go s.Listen(listen)
}

// StopServer 停止服务
func (s *Service) StopServer() {
	s.webSocketListener.Close()
	s.RpcManage.Stop()
}

// HandleNotice 处理服务通知
func (s *Service) HandleNotice(data []any) {
}

// Listen server listen
func (s *Service) Listen(listen string) {
	s.webSocketListener.Listen(listen)
}
